from django.shortcuts import render

# Create your views here.
# -*- coding: utf-8 -*-

import os
import time
from rest_framework import status
from rest_framework.response import Response
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from ops.devops.models import Notification
from dvadmin.system.models import Users
from ops.utils.send_email import mail


# 模板载入方法
from django.template import loader


class NotificationSerializer(CustomModelSerializer):
    """
    devops-序列化器
    """
    class Meta:
        model = Notification
        fields = '__all__'
        # exclude = ['passwd']
        read_only_fields = ["id"]


class NotificationViewSet(CustomModelViewSet):
    """
    devops接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    exclude_field = ['passwd']
    queryset = Notification.objects.all()
    serializer_class = NotificationSerializer
    extra_filter_backends = []
    permission_classes = []
    search_fields = ["sender", "receivers", "project", "type"]

    def create(self, request, *args, **kwargs):
        # 获取post提交的body数据
        data = request.POST.copy()
        files = request.FILES.getlist('files')
        subject = '{0}-{1}-{2}'.\
            format(data.get('type'), data.get('project'), time.strftime("%Y%m%d%H%M", time.localtime()))

        html_template_file = os.path.join('html', 'notification.html')

        # 获取发送者name和接收者邮箱地址
        data['sender'] = self.request.user.username
        receivers = data.get('receivers')

        # 获取接收者的信息
        users_info = Users.objects.filter(id__in=receivers.split(',')).values()
        receivers = [x.get('username') for x in users_info]
        email_addr = [x.get('email') for x in users_info]
        data['receivers'] = ','.join(receivers)
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)

        # 载入邮件模板
        content = loader.render_to_string(html_template_file, data)
        # 以html格式发送邮件
        data = mail(receivers=list(filter(None, email_addr)),
                    subject=subject, content=content, _subtype='html', files=files)
        self.perform_create(serializer)
        if data.get('code') == 2000:
            return Response(data, status=status.HTTP_200_OK)
        return Response(data, status=status.HTTP_400_BAD_REQUEST)
